import React, { useRef, useEffect, useState, Fragment } from 'react';
import cmdbres from '@/data/cmdbres';
import request from '@/utils/request';
import './index.less';
import G6 from '@antv/g6';
import registerEdge from '@/modules/topology/modelTopology/config/register-edge.js';
import registerNode from './config/register-node';
import { G6ToolBar, G6Menu, G6Tooltip } from './config/register-plugins';
import { defaultNodeConfig, defaultEdgeConfig, defaultLayout } from './config/default';
import { initData } from './config/utils';
import { nodeMouseFn } from '@/modules/topology/utils';
import HelpTipModal from '../components/helpTipModal';
import DetailsModal from './components/detailsModal';
const GRAPH_ID = 'resource-graph-container';

const resTopology = ({ history, cmUnid, visible, info }) => {
    const domRef = useRef(null);
    const graphRef = useRef(null);
    let graph = graphRef.current;
    const [showHelp, setShowHelp] = useState(false);
    const [detailInfo, setDetailInfo] = useState({});
    const [showDetailModal, setShowDetailModal] = useState(false);
    const [topoData, setTopoData] = useState([]);

    const queryGraphicalRelationData = async () => {
        if (!cmUnid) return;
        try {
            let res = await request({
                ...cmdbres.queryGraphicalRelationData,
                params: {
                    id: cmUnid,
                },
            });
            if (res && res.code == 200) {
                if (res.data.resourceNodes) {
                    setTopoData(res.data);
                } else {
                    setTopoData({ resourceNodes: [info] });
                }
            }
        } catch (error) {
            setTopoData({ resourceNodes: [info] });
        }
    };

    useEffect(() => {
        if (visible) queryGraphicalRelationData();
    }, [cmUnid, visible]);

    useEffect(() => {
        fetchLayout();

        return () => {
            if (graph) {
                graph.destroy();
            }
        };
    }, [topoData]);

    const fetchLayout = async () => {
        if (!topoData) return;
        const data = initData(topoData, cmUnid);

        graph = createGraphic();
        graph.read(data);
        // 关闭局部渲染解决缩放或者拖拽引起的残影问题（关闭会影响性能，临时解决办法）
        graph.get('canvas').set('localRefresh', false);
        bindEvents();
    };

    const createGraphic = () => {
        // 注册自定义节点
        registerEdge(G6);
        // 注册自定义边
        registerNode(G6);

        const container = document.getElementById(GRAPH_ID);
        const tree = new G6.Graph({
            container: domRef.current,
            width: container.offsetWidth,
            height: container.offsetHeight,
            fitCenter: true,
            defaultNode: defaultNodeConfig,
            defaultEdge: defaultEdgeConfig,
            layout: defaultLayout,
            modes: {
                default: ['drag-canvas', 'drag-node', 'zoom-canvas'],
            },
            plugins: [
                new G6.Grid(),
                new G6.Minimap({
                    size: [200, 150],
                }),
                G6Menu(G6, menuHandles),
                G6ToolBar(G6, toolBarHandles),
                G6Tooltip(G6),
            ],
        });

        graphRef.current = tree;
        return tree;
    };

    const bindEvents = () => {
        graph.on('node:mouseenter', (evt) => nodeMouseFn(evt, true, graph));
        graph.on('node:mouseleave', (evt) => nodeMouseFn(evt, false, graph));

        graph.on('edge:mouseleave', (evt) => {
            const edge = evt.item;
            graph.setItemState(edge, 'hover', false);
        });
    };

    const menuHandles = {
        queryDetail(item) {
            const model = item.getModel();
            setDetailInfo(model);
            setShowDetailModal(true);
            if (model.cm_unid == cmUnid) return;
            // history.push({
            //     pathname: "/resource/catalog/detail/" + model.cm_module_id,
            //     state: {info: model.info, moduleData: model.moduleDefinitions}
            // })
        },
    };

    const toolBarHandles = {
        defaultSize() {
            graph.zoomTo(1);
        },
        // 缩小
        zoomOut() {
            graph.zoom(0.9);
        },
        // 放大
        zoomIn() {
            graph.zoom(1.1);
        },
        relocation() {
            graph.fitCenter();
        },
        graphHelp() {
            setShowHelp(true);
        },
    };

    return (
        <div style={{ width: '100%', height: 500, position: 'relative', marginTop: 10 }}>
            <div ref={domRef} id={GRAPH_ID} style={{ width: '100%', height: 500 }}></div>
            <HelpTipModal
                visible={showHelp}
                setVisible={setShowHelp}
                extra={
                    <Fragment>
                        <h3 className="mb10 mt15">节点:</h3>
                        <p>单击右键，菜单支持【查看详情】操作</p>
                    </Fragment>
                }
            />
            <DetailsModal visible={showDetailModal} setVisible={setShowDetailModal} info={detailInfo} />
        </div>
    );
};

export default resTopology;
